package com.example.imgup;

import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.intent.Intents.intended;
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.isRoot;
import static androidx.test.espresso.matcher.ViewMatchers.withId;

import androidx.test.espresso.action.ViewActions;
import androidx.test.espresso.intent.Intents;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivity2Test {

    @Rule
    public ActivityScenarioRule<MainActivity2> activityScenarioRule =
            new ActivityScenarioRule<>(MainActivity2.class);

    @Before
    public void setUp() {
        Intents.init(); // 初始化Intents以监控Intent启动
    }

    @After
    public void tearDown() {
        Intents.release(); // 测试结束后释放资源
    }

    @Test
    public void testButtonClicks() {
        // 确保Banner已加载且至少有一个item
        onView(withId(R.id.main_banner)).check(matches(isDisplayed()));

        // 测试"About"按钮点击
        testButtonNavigation(R.id.about, SettingsActivity.class.getName());

        // 返回MainActivity2
        pressBack();

        // 测试"Locale Import"按钮点击
        testButtonNavigation(R.id.localeimport, MainActivity.class.getName());
    }

    /**
     * 测试指定按钮点击后是否打开了预期的Activity。
     *
     * @param buttonId     要点击的按钮ID
     * @param targetActivityClass 预期启动的Activity的类名
     */
    private void testButtonNavigation(int buttonId, String targetActivityClass) {
        // 点击按钮
        onView(withId(buttonId)).perform(click());

        // 验证是否启动了目标Activity
        intended(hasComponent(targetActivityClass));
    }

    private void pressBack() {
        // 模拟按下返回键
        onView(isRoot()).perform(ViewActions.pressBack());
    }
}